package ap.project.controller.main;
 
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import ap.project.controller.main.R;

public class LoginActivity extends Activity {
	private String ip;
	public String PLAYERNAME;
	public Socket socket;

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);

		final EditText name = (EditText) findViewById(R.id.name);
		final EditText editipadres = (EditText) findViewById(R.id.edtip);
		Button send = (Button) findViewById(R.id.sendbutton);
		send.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				setIpAddress(editipadres.getText().toString());
				setPlayerName(name.getText().toString());	
				if (createSocket()){
					Connection.getInstance().setUpConnection(socket);					
					Intent joystick = new Intent(getBaseContext(), ControllerActivity.class);
					joystick.putExtra("name", PLAYERNAME);
					startActivity(joystick);
				}				
			}
		});
	}
	
	/**
	 * Set player name
	 * 
	 * @param playername
	 */
	private void setPlayerName(String playername) {
		if (!(playername.equalsIgnoreCase(""))) {
			this.PLAYERNAME = playername;
		} else {
			this.PLAYERNAME = ("Soldier " + (int) (Math.random() * 1337));
		}
	}

	/**
	 * Set server ip address
	 * 
	 * @param ip
	 */
	private void setIpAddress(String ip) {
		this.ip = ip;
	}

	/**
	 * Creates socket for an open connection to the gameserver (TCP)
	 * 
	 * @return socket
	 */
	private boolean createSocket() {
		try {
			socket = new Socket(ip, Constants.PORT);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Can not connect",
					Toast.LENGTH_LONG).show();
			return false;
		}
		return true;
	}
}
